package com.ds.lens.manager.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ds.lens.data.common.util.HttpUtil;
import com.ds.lens.manager.bo.ExternalEventTaskBO;
import com.ds.lens.manager.bo.TaskBO;
import com.ds.lens.manager.scheduler.SchedulerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2020-04-22
 */
@Service
public class ExternalEventService {

    @Value(value = "${lens.service.host}")
    private String lensServiceHost;
    @Value(value = "${lens.service.external.event.timeout.task.api}")
    private String timeoutTasksApi;
    @Value(value = "${lens.service.external.event.timeout.notify.api}")
    private String timeoutNotifyApi;
    @Autowired
    private SchedulerConfig schedulerConfig;

    public void runTasks() {
        ResponseEntity responseEntity = HttpUtil.get(lensServiceHost + timeoutTasksApi, null, null, 5000);
        if (responseEntity.getStatusCode().equals(HttpStatus.OK) && null != responseEntity.getBody()) {
            JSONObject object = JSONObject.parseObject(responseEntity.getBody().toString());
            if (object.getInteger("code") != 0) {
                return;
            }
            List<ExternalEventTaskBO> tasks = object.getJSONArray("data").toJavaList(ExternalEventTaskBO.class);
            Map<String, TaskBO> taskBOMap = Maps.newHashMapWithExpectedSize(tasks.size());
            tasks.forEach(eventTaskBO -> {
                String taskKey = eventTaskBO.getExternalEventId() + "-" + eventTaskBO.getReminders();
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(1);
                params.put("externalEventId", eventTaskBO.getExternalEventId());
                taskBOMap.put(taskKey,
                        TaskBO.builder()
                                .executionTime(new Date(eventTaskBO.getExecutionTime()))
                                .method(HttpMethod.GET)
                                .taskKey(taskKey)
                                .backUrl(lensServiceHost + timeoutNotifyApi)
                                .params(params)
                                .build());
            });
            schedulerConfig.refreshTasks(taskBOMap);
        }
    }
}
